package com.tenclass.common.interceptor.request;

import cn.ilanxin.common.error.ContextExceptionV2;
import com.tenclass.common.model.CurrentUser;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

import static com.tenclass.common.constant.RequestConstant.*;

/**
 * 内部接口拦截器
 *
 * @author YIJIUE
 * @since 1.2.5
 */
public class InnerInterceptor implements IRequestInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request) {
        // 理论上来说 判断内部接口 要验证调用的IP是否注册到注册中心， 因当前采用的 K8S SERVICE 所以需要一定的开发与适配，暂时简化
        String user = request.getHeader(CURRENT_USER);
        String gateway = request.getHeader(FROM_GATEWAY);
        if (!StringUtils.isEmpty(gateway)) {
            throw new ContextExceptionV2(401, null, "非法请求");
        }
        if (!StringUtils.isEmpty(user)) {
            CurrentUser.set(URLDecoder.decode(user, StandardCharsets.UTF_8));
        }
        return true;
    }

}
